﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Trakt.Model
{
    public class AuthenticationToken : IJsonDeserializable
    {
        public string Token { get; private set; }
        public string TokenType { get; private set; }
        public string Scope { get; private set; }
        public TimeSpan ValidFor { get; private set; }
        public DateTime ExpiresUtc { get; private set; }
        public DateTime Expires { get; private set; }
        public bool Expired { get { return Expires < DateTime.Now; } }

        public AuthenticationToken(string token, string tokenType, string scope, TimeSpan validFor, DateTime expiresUtc)
        {
            Token = token;
            TokenType = tokenType;
            Scope = scope;
            ValidFor = validFor;
            ExpiresUtc = expiresUtc;
            Expires = expiresUtc.ToLocalTime();
        }

        public void Deserialize(JsonReader reader, JsonSerializer serializer)
        {
            var j = JObject.Load(reader);

#if DEBUG
            var accessToken = (string)j["access_token"];
            var refreshToken = (string)j["refresh_token"];
            Debug.Assert(accessToken != null && refreshToken != null, "Received both access and refresh token");
            Token = accessToken ?? refreshToken;
#else
            Token = (string)j["access_token"] ?? (string)j["refresh_token"];
#endif

            TokenType = (string)j["token_type"];
            Scope = (string)j["scope"];
            ValidFor = new TimeSpan(0, 0, (int)j["expires_in"]);
            ExpiresUtc = DateTime.UtcNow.Add(ValidFor);
            Expires = ExpiresUtc.ToLocalTime();
        }

        public override string ToString()
        {
            return Token;
        }
    }
}
